const m3u8Parser = window.m3u8Parser
const URLToolkit = window.URLToolkit

const queryParam = location.search
const queryObj = {}
queryParam && queryParam.substr(1).split('&').forEach(pair => {
    const arr = pair.split('=')
    queryObj[decodeURIComponent(arr[0])] = decodeURIComponent(arr[1])
})


const file = queryObj.file
const name = queryObj.name || ''

const atag = document.getElementById('da')



main() 

async function main () {
    let m3u8Content
    try {
        const m3u8Res = await fetch(file)
        m3u8Content = await m3u8Res.text()
    } catch (err) {
        console.log('fetch m3u8 error', err)
        return
    }


    console.log('m3u8Content', m3u8Content)

    const parser = new m3u8Parser.Parser()
    parser.push(m3u8Content)
    parser.end()
    const playlist = parser.manifest
    const segments = playlist.segments.map(seg => {
        return Object.assign({}, seg, {url: URLToolkit.buildAbsoluteURL(file, seg.uri)})
    })
    console.log('segments', segments)

    for (let i = 0; i < segments.length; i++) {
        const seg = segments[i]
        console.log('正在下载seg: ' + i + ' ' + seg.url)
        const segRes = await fetch(seg.url)
        seg.arrayBuffer = await segRes.arrayBuffer()
    }
    console.log(segments)

    const bufferList = segments.map(seg => seg.arrayBuffer)
    console.log(bufferList)

    const blob = new Blob(bufferList)
    const url = URL.createObjectURL(blob)
    
    atag.href = url
    console.log(url)
}